package edu.csu.smartpark.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import edu.csu.smartpark.model.properties.AliyunOssProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/*
* @Description: 连接阿里云oss，上传下载文件工具包
* @Author: LZY
* @Date: 2021/4/13 14:23
*/
@Component
public class OssUtil {

    private  static final Logger log = LoggerFactory.getLogger(OssUtil.class);

    @Autowired
    private AliyunOssProperties properties;

    public OSSClient getClient(){
        OSSClient client = new OSSClient(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        if (client == null){
            log.warn("Oss client open fail");
        }
        return client;
    }

    public void  putObject(String objectName, InputStream inputStream){
        OSSClient client = getClient();
        if (client != null){
            client.putObject(properties.getBucketName(), objectName, inputStream);
            log.info(String.format("OSS put object: %s success", objectName));
            client.shutdown();
            return;
        }
        log.info(String.format("OSS put object: %s fail", objectName));
    }

    public InputStream getObject(String objectName){
        OSSClient client = getClient();
        if (client != null){
            OSSObject object = client.getObject(properties.getBucketName(), objectName);
            InputStream content = object.getObjectContent();
            client.shutdown();
            log.info(String.format("Oss get object: %s success", objectName));
            return content;
        }
        log.info(String.format("Oss get object: %s fail", objectName));
        return null;
    }

    public void deleteObject(String objectName){
        OSSClient client = getClient();
        if (client != null){
            client.deleteObject(properties.getBucketName(), objectName);
            log.info(String.format("Oss delete object: %s success", objectName));
            client.shutdown();
            return;
        }
        log.info(String.format("Oss delete object: %s fail", objectName));
    }

}
